/**
 * 会议服务 - 处理与后端API的交互
 */

import axios from 'axios';
import { ElMessage } from 'element-plus';
import UserService from './UserService.js';
import router from '../router';

// 创建axios实例
const api = axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  validateStatus: status => status >= 200 && status < 300
});

// 请求拦截器，自动加token
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token') || (UserService.getCurrentUser && UserService.getCurrentUser().token) || '';
  if (token) {
    config.headers.token = token;
  }
  return config;
});

// 响应拦截器
api.interceptors.response.use(
  (response) => {

    return response
  },
  (error) => {
    //如果响应的状态码为401, 则路由到登录页面
    console.log('响应错误:', error);
    if (error.response.status === 401) {
      ElMessage.error('登录失效, 请重新登录')
      router.push('/login')
    } else {
      ElMessage.success('接口访问异常')
    }
    return Promise.reject(error)
  }
);


export default {
  /**
   * 获取会议列表
   * @param {Object} params 筛选参数
   * @returns {Promise} 返回会议列表
   */
  getMeetings(params = {}) {
    // 创建一个新的参数对象，避免修改原始对象
    const queryParams = { ...params };

    // 添加当前用户ID参数
    queryParams.currentUserId = UserService.getCurrentUserId();

    // 确保日期格式正确
    if (queryParams.startTime) {
      console.log('MeetingService - 发送开始时间筛选:', queryParams.startTime);
    }

    console.log('MeetingService - 发送请求参数:', queryParams);

    return api.get('/api/meetings/list', { params: queryParams })
      .then(response => {
        console.log('MeetingService - 获取会议列表响应:', response.data);
        return response.data;
      })
      .catch(error => {
        console.error('获取会议列表失败:', error);
        throw error;
      });
  },

  /**
   * 创建会议
   * @param {Object} meeting 会议信息
   * @param {Number} currentUserId 当前用户ID
   * @returns {Promise} 返回创建结果
   */
  createMeeting(meeting, currentUserId) {
    console.log('MeetingService - 创建会议，当前用户ID:', currentUserId);
    console.log('MeetingService - 当前用户ID类型:', typeof currentUserId);
    console.log('MeetingService - 当前用户ID值:', currentUserId);

    // 验证currentUserId是否有效
    if (currentUserId === undefined || currentUserId === null || currentUserId === 0) {
      console.error('MeetingService - 错误：currentUserId无效:', currentUserId);
      throw new Error('当前用户ID无效');
    }

    // 设置创建者ID到请求体中
    meeting.creatPersonId = currentUserId;

    // 处理内容字段可能的不一致
    const meetingData = { ...meeting };

    // 确保两个内容字段同步
    if (meetingData.meetingCcontent && !meetingData.meetingContent) {
      meetingData.meetingContent = meetingData.meetingCcontent;
    } else if (meetingData.meetingContent && !meetingData.meetingCcontent) {
      meetingData.meetingContent = meetingData.meetingCcontent;
    }

    console.log('MeetingService - 创建会议数据:', meetingData);
    console.log('MeetingService - creatPersonId字段值:', meetingData.creatPersonId);

    // 将currentUserId作为URL查询参数传递
    return api.post('/api/meetings/create', meetingData, {
      params: { currentUserId }
    })
      .then(response => {
        console.log('MeetingService - 创建会议响应:', response.data);
        return response.data;
      })
      .catch(error => {
        console.error('创建会议失败:', error);
        throw error;
      });
  },

  /**
   * 更新会议
   * @param {Object} meeting 会议信息
   * @returns {Promise} 返回更新结果
   */
  updateMeeting(meeting) {
    // 处理内容字段可能的不一致
    const meetingData = { ...meeting };

    // 确保两个内容字段同步
    if (meetingData.meetingCcontent && !meetingData.meetingContent) {
      meetingData.meetingContent = meetingData.meetingCcontent;
    } else if (meetingData.meetingContent && !meetingData.meetingCcontent) {
      meetingData.meetingCcontent = meetingData.meetingContent;
    }

    console.log('MeetingService - 更新会议数据:', meetingData);

    const isAdmin = UserService.isAdmin();
    return api.put(`/api/meetings/update/${isAdmin}`, meetingData)
      .then(response => {
        console.log('MeetingService - 更新会议响应:', response.data);
        return response.data;
      })
      .catch(error => {
        console.error('更新会议失败:', error);
        throw error;
      });
  },

  /**
   * 删除会议
   * @param {Number} meetingId 会议ID
   * @returns {Promise} 返回删除结果
   */
  deleteMeeting(meetingId) {
    return api.delete('/api/meetings/delete', { params: { meetingId } })
      .then(response => {
        console.log('MeetingService - 删除会议响应:', response.data);
        return response.data;
      })
      .catch(error => {
        console.error('删除会议失败:', error);
        throw error;
      });
  },

  /**
   * 审核会议
   * @param {Number} meetingId 会议ID
   * @param {Number} status 审核状态 (1: 通过, 2: 拒绝)
   * @returns {Promise} 返回审核结果
   */
  reviewMeeting(meetingId, status) {
    return api.post('/api/meetings/review', null, {
      params: { meetingId, status }
    })
      .then(response => {
        console.log('MeetingService - 审核会议响应:', response.data);
        return response.data;
      })
      .catch(error => {
        console.error('审核会议失败:', error);
        throw error;
      });
  },

  /**
   * 获取会议详情
   * @param {Number} meetingId 会议ID
   * @returns {Promise} 返回会议详情
   */
  getMeetingDetail(meetingId) {
    return api.get('/api/meetings/list', { params: { meetingId } })
      .then(response => {
        if (response.data && response.data.code === 200 && response.data.data) {
          // 确保返回的数据中找到匹配的会议ID
          const meetings = response.data.data;
          const meeting = meetings.find(m => m.meetingId === meetingId);

          if (meeting) {
            // 处理内容字段可能的不一致
            if (meeting.meetingContent && !meeting.meetingCcontent) {
              meeting.meetingCcontent = meeting.meetingContent;
            } else if (meeting.meetingCcontent && !meeting.meetingContent) {
              meeting.meetingContent = meeting.meetingCcontent;
            }

            console.log('MeetingService - 获取会议详情成功:', meeting);
            return meeting;
          } else if (meetings.length > 0) {
            console.warn('未找到ID匹配的会议，但有其他会议数据');
            return null;
          }
        }
        throw new Error('获取会议详情失败');
      })
      .catch(error => {
        console.error('获取会议详情失败:', error);
        throw error;
      });
  },

  /**
   * 获取会议列表（分页）
   * @param {Object} params 筛选参数和分页参数
   * @returns {Promise} 返回分页会议列表
   */
  getMeetingsWithPage(params = {}) {
    // 创建一个新的参数对象，避免修改原始对象
    const queryParams = { ...params };

    // 添加当前用户ID参数
    queryParams.currentUserId = UserService.getCurrentUserId();

    // 确保日期格式正确
    if (queryParams.startTime) {
      console.log('MeetingService - 发送开始时间筛选:', queryParams.startTime);
    }

    console.log('MeetingService - 发送分页请求参数:', queryParams);

    return api.get('/api/meetings/list-page', { params: queryParams })
      .then(response => {
        console.log('MeetingService - 获取分页会议列表响应:', response.data);
        return response.data;
      })
      .catch(error => {
        console.error('获取分页会议列表失败:', error);
        throw error;
      });
  }
}; 